let config = require("./config.js");
/**
 * 后台API请求
 * @param {*对象参数} params 
 * @param {*回调函数} callback 
 */
export class Request {
	static HOST = config.default.service.requestUrl;
	constructor(url = null, data) {
		this.url = url;
	}
	request(method, params, callback) {
		// console.log(`请求成功${Request.HOST}${this.url}`);
		uni.request({
			url: `${Request.HOST}${this.url}`, //仅为示例，并非真实接口地址。
			method: method(),
			data: params(),
			header: {
				'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
			},
			success: (setData) => {
				//接口成功回调
				this.success = function(){
					callback(setData);
				}
				//HTTP状态码
				this.JudgeCode(setData.statusCode);
			}
		});
	}
	
	/**
	* 选择图片上传接口 
	* @param {Object} 
	* params：上传文件传参
	* callback：回调函数
	*/
	uploadImage(params, callback){
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			success: (chooseImageRes) => {
				// console.log(chooseImageRes)
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.uploadFile({
					url: `${Request.HOST}${this.url}`,
					filePath: tempFilePaths[0],
					name: 'file',
					formData: params(),
					success: (setData) => {
						//接口成功回调
						this.success = function(){
							callback(JSON.parse(setData.data)); 
						}
						
						//HTTP状态码
						this.JudgeCode(setData.statusCode);

						//判断图片是否有违规
						let ImageCode = JSON.parse(setData.data).code;
						if(ImageCode == -3){
							this.showToast('图片违规');
							return;
						} else if (ImageCode == 1){
							this.showToast('图片上传成功');
						} else {
							this.showToast(JSON.parse(setData.data).msg);
						}
					}
				});
			}
		})
	}
	
	/**
	 * 显示消息提示框 showToast
	 * setTimeout 交互显示后触发回调函数
	 */
	showToast(title, icon = 'none', setTimeout = Object) {
		uni.showToast({
			title: title,
			position: 'center', //position 值说明（仅App生效）
			icon: icon,
			duration: 2000,
			mask: false, //是否显示透明蒙层，防止触摸穿透，默认：false
		});
		//接口报错，延迟跳转首页
		setTimeout();
		return;
	}
	
	/**
	 * 判断 请求状态码
	 */
	JudgeCode(statusCode){
		switch (statusCode) {
			case 500:
				this.showToast('内部服务器错误', 'none', () => {
					setTimeout(() => {
						//报错跳转首页，重新登陆
						uni.switchTab({
							url: '/pages/index/index',
							complete: (params) => {
								console.log('已重新加载/pages/index/index路径')
							},
						});
					}, 1000); //rest：param1, param2, ..., paramN 等附加参数，它们会作为参数传递给回调函数
				});
				break;
			case 404:
				this.showToast('请求的资源不存在');
				break;
			case 401:
				this.showToast('网络出错');
				break;
			case 200:
				this.success();
				break;
			default:
		}
	}
}
